<link type="text/css" rel="stylesheet" href="__CDN__comp/wxuploader.css?v=__APP_VERSION__" />
<link type="text/css" rel="stylesheet" href="__CDN__admin/theme/simplex.min.css" />
<!-- bootstrap.css -->
<style>
#upload_picture:hover{ cursor: pointer; }
/*调整cosmo样式*/
ul,ol,dl{ margin-bottom: 0; }
dd{ line-height: inherit; }
a:hover,a:focus{ text-decoration: none; }
.admin-header .avatar {  height: 40px;padding-top: 4px; }
.admin-main {  margin-top: 40px; }
.thumbnail{ padding: 0!important; }
.img-selected:after{  width:117px !important; }
.wxuploaderimg .img-preview img{  width:100px !important; }
.wxuploaderimg .img-preview .edit_pic_wrp{
  background-color: rgba(229,229,229,0.2)!important;
  width:100px;height:100px;
}
.wxuploaderimg .img-preview .edit_pic_wrp a{
  width:100px;height:100px;left:0;bottom:0;margin-left: 0;padding-top: 40px;
}
@media (min-width: 768px) { }
@media (min-width: 992px) { }
@media (min-width: 1200px) {  }
</style>
<script type="text/javascript" src="__CDN__bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link type="text/css" rel="stylesheet" href="__PUBLIC__static/jquery-uploadify/3.2.1/uploadify.css" />
<script type="text/javascript" src="__PUBLIC__static/jquery-uploadify/3.2.1/jquery.uploadify.min.js"></script>

<!-- <link rel="stylesheet" type="text/css" media="all" href="__CDN__jquery-datetimepicker/jquery.datetimepicker.css">
<script type="text/javascript" src="__CDN__jquery-datetimepicker/jquery.datetimepicker.js"></script> -->

<!-- Modal -->
<div class="modal " id="wxuploadimg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="padding-left: 200px!important;padding-top: 50px!important">
  <div class="modal-dialog">
    <div class="modal-content" style="width:702px;">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">选择图片  (善用搜索,上传不了可尝试改名上传)</h4>
      </div>
      <div class="modal-body clearfix">

        <div class="col-lg-12 col-md-12 form-inline p0">
          <input type="text" name="time" class="time form-control" placeholder="哪一天">
          <input type="text" name="q"  class="form-control" placeholder="文件名" />
          <button class="btn btn-sm btn-primary js_search" type="button" ><i class="fa fa-search"></i>查找</button>
          <button class="btn btn-sm btn-primary" type="button" onclick="removeImg()"><i class=""></i>删除</button>
        </div>
        <!--<div class="col-lg-2 col-md-2">

        </div>-->
        <div class="col-lg-12 col-md-12 p0">
          <div class="btns pull-right"><a href="javascript:void(0);" id="upload_picture"><i class="fa fa-upload"></i>本地上传</a>
          </div>
          <div class="imgs-container pull-left">
            <div class="loading">
              <img src="__CDN__common/loading.gif" />
            </div>
            <div class="imgs-list clearfix"></div>
            <div class="pager"></div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <div class="pull-left">已选<span class="js_checked"></span>张,可选<span class="js_total"></span>张</div>
        <button type="button" class="btn btn-primary js_check_img"><i class="fa fa-check"></i>确定</button>
        <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times-circle"></i>取消</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
  // 放到服务器端 2018-05-24 10:34:37
  // appendImgList() 组装图片地址可能用到
  // var img_show_url = "{ :config('picture_url') }";
  // function getImgUrl(id,size){
  //   return img_show_url+'?id='+id+'&size='+size;
  // }

  Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
    this.splice(index, 1);
    }
  };
  var imgIds = []; // 选中的图片 ids
  function getImg(d){
    var id = $(d).find('img').data('imageid');
    if(!$(d).hasClass("img-selected")){
      if($.inArray(id,imgIds) == -1){
        imgIds.push(id);
      }
    }else{
      if($.inArray(id,imgIds) != -1) {
        imgIds.remove(id);
      }
    }
  }

  function removeImg(){
    //console.log(imgIds);
    if(confirm("你真的要删除图片吗？如果有商品正在使用将无法正常显示！！！")){
      $.ajax({
        type:"POST",
        url:"{:url('File/del')}",
        data:{
          imgIds:imgIds
        },
        context:window,
        dataType: "json",
        success:function(data){
          //console.log(data);
          if(data.code == 1){
              console.info(data);
              imgIds.length = 0;
              window.wxuploadimg.setChecked(0);
              window.wxuploadimg.queryImgList();
          }else{
              alert(data.msg);
          }
        }
      })
      return false;
    }

    return false;

  }

  window.wxuploadimg = (function() {
    var pager = {
      index: 0,
      size: 10, //页面数
    };
    var checked = 0;
    var hadBind = false;
    /**
     * 将数据组合成HTML
     */
    function appendImgList(list) {
      if (list) {
        var $cont = $("#wxuploadimg .imgs-list").empty(),$item,item;
        for (var i = 0; i < list.length; i++) {
          item = list[i];
          var imgsrc = item.imgurl;//放到服务器端,getImgUrl(item.id,120);
          $item = $("<div class='img-item ' onclick='getImg(this)'><img class='img-responsive  thumbnail js_img_click' data-imageid='"+ item.id+"' src='" + imgsrc  + "' title='"+item.ori_name+"'/><p class='img-desc'>"+item.ori_name+"</p></div>");
          $cont.append($item);
        }
      }else{
        $("#wxuploadimg .imgs-list").html("");
      }
    }

    /**
     * 处理分页点击事件
     */
    function pagerClick(){

      $("#wxuploadimg .imgs-container").click(function(ev){
        $target = $(ev.target);
        if($target.hasClass("img-selected")){
          $target.removeClass("img-selected");
          checked--;
          $("#wxuploadimg .js_checked").text(parseInt($("#wxuploadimg .js_checked").text())-1);
        }
        if($target.hasClass("js_img_click")){
                    console.log("*******************************************");
                    console.log(checked,window.wxuploadimg.setting.MaxChecked);
                    console.log("*******************************************");
          if(checked == window.wxuploadimg.setting.MaxChecked){
            var len = $(".img-preview img",window.wxuploadimg.current).length;

            $.scojs_message('最多可选'+(wxuploadimg.setting.MaxChecked-len)+'张!', $.scojs_message.TYPE_ERROR);
          }

          if(checked < window.wxuploadimg.setting.MaxChecked){
            $target.parent().addClass("img-selected");
            checked++;
            $("#wxuploadimg .js_checked").text(parseInt($("#wxuploadimg .js_checked").text())+1);
          }
        }
        ev.preventDefault();
        if($target.hasClass("num")){
          pager.index = parseInt($target.text());
          queryImgList();
          ev.preventDefault();
        }else if($target.hasClass("next")){
          pager.index = pager.index+1;
          queryImgList();
          ev.preventDefault();
        }else if($target.hasClass("prev")){
          pager.index = pager.index-1;
          if(pager.index <0 ){
            pager.index = 0;
          }
          queryImgList();
          ev.preventDefault();
        }

      });
    }
    /**
     * 向服务器请求数据
     */
    function queryImgList() {
      var q = $("#wxuploadimg input[name='q']").val();
      var time = $("#wxuploadimg input[name='time']").val();
      $.ajax({
        type: "post",
        url: "{:url('admin/file/picturelist')}?p="+wxuploadimg.pager.index,
        data: {
          time:time,
          q:q,
          size: wxuploadimg.pager.size
        },
        dataType: "json",
        beforeSend: function() {
          $("#wxuploadimg .imgs-container .loading").removeClass("hidden");
        }
      }).done(function(data) {
        if (data.status) {
          var info = data.info;
          var list = info.list;
          var show = info.show;
          appendImgList(list);
          $("#wxuploadimg .imgs-container .pager").html(show);
        }
      }).always(function() {
        $("#wxuploadimg .imgs-container .loading").addClass("hidden");
      });
    }

    function clearSelected(){
      $("#wxuploadimg .img-item.img-selected").removeClass("img-selected");
      imgIds = [];
    }
    var i=0;
    /**
     * callback
     * @param {Object} cont 触发模态框的选择器
     * @param {Object} callback 选中图片后的触发器
     */
    function init(setting){
      if(setting.callback){
        wxuploadimg.callBack = setting.callback;
      }
      if(setting.reinit) {
          wxuploadimg.setting.reinit = false;
      }
      wxuploadimg.setting = $.extend({},wxuploadimg.setting, setting);
      pager.size = setting.size || pager.size;
      //上传按钮点击处理
      $(".add",wxuploadimg.setting.cont).each(function(index,item){
        $(item).click(function(ev){
          $ele = $(this);
            // if($ele.hasClass('add')){
            window.wxuploadimg.current =  $ele.parent();
            open($(window.wxuploadimg.current).attr("data-maxitems"));
            clearSelected();
            // }
        });
      });
      queryImgList();
      // 预览图片 选择
      $(".img-preview",window.wxuploadimg.cont).click(function(ev){
          var obj = window.wxuploadimg.current;
          var tar = ev.target;
          window.wxuploadimg.current = $(tar).parents(".wxuploaderimg");
          //console.log("当前点击的是",$(tar));
          if($(tar).hasClass("js_delete")){
              // console.log($(tar));
              $(tar,obj).parents(".img-item").remove();
              var len = $(".img-preview img",obj).length;
              // console.log($(".img-preview img",obj));
              // console.log(len);
              //已全部选择
              if(len == 0){
                  $(".img-preview",obj).hide();
                  $(obj).removeClass("checked");
                  $(".add",obj).show();
              }
              //还剩余
              if(len < wxuploadimg.setting.MaxChecked){
                  $(".add",obj).show();
              }
          }
          ev.preventDefault();
          ev.stopPropagation();
      });

      if(!hadBind){
        //使用此标志来防止 当调用多次init方法来初始化时，#wxuploadimg绑定了多次click监听器
        pagerClick();
        //选中图片
        $("#wxuploadimg .js_check_img").click(function(){

          window.wxuploadimg.setting.callback = wxuploadimg.setting.callback || callback;
          window.wxuploadimg.setting.callback.apply(this,$("#wxuploadimg .img-selected img"));
          if(checked == wxuploadimg.setting.MaxChecked){
            $(".add",window.wxuploadimg.current).hide();
          }
          $('#wxuploadimg').modal("hide");
        });

        //查找
        $(".js_search").click(function(){
          wxuploadimg.pager.index = 1;
          imgIds.length = 0;
          window.wxuploadimg.setChecked(0);
          $("#wxuploadimg .js_checked").text(0);
          $("#wxuploadimg .js_total").text(wxuploadimg.setting.MaxChecked);
          window.wxuploadimg.queryImgList();
        });//END 查找

      }
      hadBind = true;
    }

    function open(maxchecked){
      checked = $(".img-preview img",wxuploadimg.current).length ;
      wxuploadimg.setting.MaxChecked = maxchecked || wxuploadimg.setting.MaxChecked;
      $("#wxuploadimg .js_checked").text(0);
      $("#wxuploadimg .js_total").text(wxuploadimg.setting.MaxChecked - checked);
      $('#wxuploadimg').modal("show");
    }
    function callback(){
      var data = arguments;
      for(var i=0;i<data.length;i++){
        var $ele = $('<div class="pull-left clearfix img-item"><div class="edit_pic_wrp"><a href="javascript:;" class="fa fa-lg fa-trash js_delete"></a></div></div>');
        $(".img-preview",wxuploadimg.current).append($ele).css("display","inline-block");//.show();
        $ele.prepend($(data[i]).clone());

      }
    }

    //设置选中的数量
    function setChecked(newchecked){
        checked = newchecked;
    }
    return {
      setting: {
        MaxChecked:1,//最多可选图片数
        size: 10, //每页图片数
        callback:null //默认回调函数
      },

      setChecked:setChecked,
      current:null,
      pager: pager,
      appendImgList:appendImgList,
      pagerClick:pagerClick,
      queryImgList:queryImgList,
      init:init,
    };

  })();

  //上传图片
  /* 初始化上传插件  */
  $("#wxuploadimg #upload_picture").uploadify({
    'buttonClass': 'btn btn-primary btn-sm',
    "height": "30px",
    "swf": "__PUBLIC__static/jquery-uploadify/3.2.1/uploadify.swf",
    "fileObjName": "wxshop", //wxshop
    "buttonText": "<i class='fa fa-upload'></i>本地上传",
    "uploader": "{:url('File/uploadUserPicture',['session_id'=>session_id()])}",
    "width": 120,
    'removeTimeout': 1,
    'fileTypeExts': '*.jpg; *.png; *.gif;*.jpeg',
    "onUploadSuccess": uploadPicture
  });

  function uploadPicture(file, data) {
    var data = $.parseJSON(data);
    if (data.status) {
      // var src = '';
      // data = data.info;
      // var imgsrc = img_show_url+data.id;
      // // var imgsrc = data.imgurl;
      // // if(!imgsrc){
      // //   var url = {php}$url = config('PICTURE_REMOTE_URL')==NULL?config('SITE_URL'):config('PICTURE_REMOTE_URL');echo "'$url'"{/php};
      // //   imgsrc = url+data.path;
      // // }
      // $item = $("<div class='img-item '  onclick='getImg(this)'><img class='img-responsive  thumbnail js_img_click' data-imageid='"+ data.id+"' src='" + imgsrc + "' title='"+data.ori_name+"'/><p class='img-desc'>"+data.ori_name+"</p></div>");
      // $(".imgs-list").prepend($item);

      //重新查询第一页
      window.wxuploadimg.pager.index = 1;
      window.wxuploadimg.queryImgList();
    } else {
      $.scojs_message(data.info, $.scojs_message.TYPE_ERROR);
    }
  }
  $(function(){
    // .wxuploaderimg 触发区域
    // #wxuploaderimg modal
    $('.ajax-post').on('click','body',function(){
      var flag = true,img;
      $('.wxuploaderimg').each(function(index, el) {
        $el = $(el);
        img = $el.find('.img-preview img').map(function(i,el) { return el.getAttribute('data-imageid'); }).get().join(',');
        $el.prev('input').val(img); // 修改图片表单域
      });
      return flag;
    });
    // var init = '[autoinit]';
    // if(init == 'true'){
      wxuploadimg.init({cont:".wxuploaderimg"});
    // }
  })

  // 模块化 datetimepicker
  layui.use(['datetimepicker'],function(){
    var $ = layui.$;
    if($.fn.datetimepicker){
        $("#wxuploadimg input.time").datetimepicker({
          lang: 'ch',
          timepicker:false,
          format:'Y-m-d',
          allowBlank : true,
        });
        console.log("日期初始化成功！");
    }
  });
</script>